package models

import (
	"github.com/astaxie/beego/orm"
	"strconv"
)

type ArticleTypeModels struct {
}

type ArticleType struct {
	Id    int64  `orm:pk;auto;size(11)`
	Title string `orm:size(200);default("")`
	Pid   int64
	Type  int
	Sort  int
}

func init() {
	orm.RegisterModel(new(ArticleType))
}

func (a *ArticleTypeModels) Get(id int64) (ArticleType, error) {
	o := orm.NewOrm()
	at := ArticleType{Id: id}
	err := o.Read(&at)
	return at, err
}

func (a *ArticleTypeModels) Query() ([]ArticleType, error) {
	var list []ArticleType
	ps := getQueryTable("article_type")
	_, err := ps.All(&list)
	return list, err
}

func (a *ArticleTypeModels) Add(maps map[string]interface{}) (int64, error) {
	at := ArticleType{}
	at.Title = maps["title"].(string)
	at.Pid, _ = strconv.ParseInt(maps["pid"].(string), 10, 64)
	if maps["type"] != nil {
		at.Type, _ = strconv.Atoi(maps["type"].(string))
	}
	if maps["sort"] != nil {
		at.Sort, _ = strconv.Atoi(maps["sort"].(string))
	} else {
		at.Sort = 100
	}
	o := orm.NewOrm()
	return o.Insert(&at)
}

func (a *ArticleTypeModels) Edit(maps map[string]interface{}) (int64, error) {
	at := ArticleType{}
	at.Id, _ = strconv.ParseInt(maps["id"].(string), 10, 64)
	o := orm.NewOrm()
	_ = o.Read(&at)
	if maps["title"] != nil {
		at.Title = maps["title"].(string)
	}
	if maps["type"] != nil {
		at.Type, _ = strconv.Atoi(maps["type"].(string))
	}
	if maps["sort"] != nil {
		at.Sort, _ = strconv.Atoi(maps["sort"].(string))
	}
	return o.Update(&at)
}

func (a *ArticleTypeModels) Delete(id int64) (int64, error) {
	o := orm.NewOrm()
	return o.Delete(&ArticleType{Id: id})
}
